const {
    express,
    db_mysql,
    errorData,
    strLen,
    Util,
    host,
    port,
    downLoadImg,
    platform,
    protoco
} = require('./common-req.js')
const fs = require('fs');
const router = express.Router();
const https = require('https');
const http = require('http')
var sysPath = require('path');
//引入multer模块
const multer = require('multer');

//设置上传的文件夹
const upload = multer({
    dest: "public/uploadimg/images"
}) //设定图片上传后的路径

let imgIndentify = {};
//图像识别
var AipImageClassifyClient = require("baidu-aip-sdk").imageClassify;
var AipImageClassifyClient = require("baidu-aip-sdk").imageClassify;
var HttpClient = require("baidu-aip-sdk").HttpClient;
HttpClient.setRequestOptions({
    timeout: 5000
});
// 设置APPID/AK/SK
var APP_ID = "23926663";
var API_KEY = "oqVso6ddST92Pw6oDcWPNwHi";
var SECRET_KEY = "rX5bxyoxoOmboXXTGk5YITHXhQj7eY7Z";

let authUrl = `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${API_KEY}&client_secret=${SECRET_KEY}`;


// 新建一个对象，建议只保存一个对象调用服务接口
var client = new AipImageClassifyClient(APP_ID, API_KEY, SECRET_KEY);

// 调用通用物体识别
var options = {};
options["baike_num"] = "5";

// 图片识别API
imgIndentify.imgMatch = function(image, options, cb) {
    client.plantDetect(image, options).then(async function(result) {
        console.log('识别结果11', result.result)
        let t_res = result.result.reduce((prev, cur) => {
            if (cur.baike_info['image_url']) {
                prev.push(cur)
            }
            return prev
        }, [])
        let pRes = t_res.slice(0, t_res.length < 3 ? t_res.length : 3);
        console.log('识别结果', pRes)
        let resData = {
            data: {
                main: {},
                relative: []
            },
            status: 0,
            msg: '获取数据成功'
        }
        if(platform === 'linux') {
            https.get(`${protoco}${host}:${port}/plantknow/reptile?search=${pRes[0].name}`, (picRes) => {
                console.log('picRes')
            })
        } else {
            http.get(`${protoco}${host}:${port}/plantknow/reptile?search=${pRes[0].name}`, (picRes) => {
                console.log('picRes1')
            })
        }
        for(var k in pRes) {
            if (!pRes[k].baike_info['image_url']) continue;
            var imgUrl = pRes[k].baike_info.image_url;
            console.log(imgUrl)
            var hostIndex = imgUrl.indexOf('/', 10);
            var fileIndex = imgUrl.lastIndexOf('pic/');
            var fileIndexLast = imgUrl.lastIndexOf('?') > -1 ? imgUrl.lastIndexOf('?') : imgUrl.length - 1;
            var hostName = imgUrl.substring(0, hostIndex + 1);
            var fileName = imgUrl.substring(fileIndex + 4, fileIndexLast)
            var path = sysPath.join(__dirname, `../public/images/${fileName}.jpg`)
            var params = {
                url: imgUrl,
                hostName: hostName,
                fileName: fileName,
                path: path
            }
            // 读取图片
            await downLoadImg(params);
            pRes[k].baike_info.image_url = `/public/images/${fileName}.jpg`;
        }
        resData.data.main = pRes[0];
        resData.data.relative.push(...pRes.slice(1));
        cb && cb(resData);
    }).catch(function(err) {
        // 如果发生网络错误
        console.log(err);
    });
}

/**
 * 清空上传的文件
 * */
function delDir(path){
    let files = [];
    if(fs.existsSync(path)){
        files = fs.readdirSync(path); // 读取文件夹
        files.forEach((file, index) => { // 遍历文件夹
            let curPath = path + "/" + file; // 拼接文件路径
            if(fs.statSync(curPath).isDirectory()){
                delDir(curPath); //递归删除文件夹
            } else {
                fs.unlinkSync(curPath); //删除文件
                console.log(curPath)
            }
        });
    }
}
setInterval(() => {
    delDir('./public/uploadimg/images');
}, 86400)
// 图片上传API
router.post('/', upload.any(), function(req, res, next) {
    console.log('识别开始，上传图片')
    try {
        const image = fs.readFileSync(req.files[0].path).toString("base64");
        var options = {};
        options["baike_num"] = "5";
        imgIndentify.imgMatch(image, options, pData => {
            res.send(pData)
        })
    } catch (e) {
        //TODO handle the exception
        console.log(e)
        res.send(e)
    }
})


module.exports = router;
